# coding=utf-8
import os, datetime
from cnnews import settings


# 保存文件
def handle_upload_file(f):
    # 文件名称
    # print(f.name)
    # # 字节大小
    # print(f.size)
    now = datetime.datetime.now()
    # 时间戳
    now_stamp = int(now.timestamp())
    # 获取文件扩展名
    extend = os.path.splitext(f.name)[1]

    # 文件名称
    file_name = str(now_stamp) + extend

    path = settings.MEDIA_ROOT + now.strftime('%Y%m%d')
    file_path = path + file_name
    # 文件路径不存在就创建
    if not os.path.exists(path):
        os.makedirs(path)
        print(path)
    with open(file_path, 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)
        # destination.close()
        print(path)
    return now.strftime('%Y%m%d') + file_name
